package com.bitc.crash.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bitc.crash.common.BaseResponse;
import com.bitc.crash.common.ErrorCode;
import com.bitc.crash.exception.BusinessException;
import com.bitc.crash.model.entity.Commodity;
import com.bitc.crash.model.vo.CommodityVO;
import com.bitc.crash.service.CommodityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;

/**
 * 商品接口
 */
@RestController
@RequestMapping("/commodity")
@Slf4j
@Tag(name = "商品接口")
public class CommodityController {

    @Resource
    private CommodityService commodityService;

    /**
     * 根据id获取商品
     */
    @GetMapping("/get/vo")
    @Operation(summary = "根据id获取商品")
    public BaseResponse<CommodityVO> getCommodityVOById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Commodity commodity = commodityService.getById(id);
        if (commodity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return BaseResponse.success(commodityService.getCommodityVO(commodity));
    }

    /**
     * 分页获取商品列表（仅管理员）
     */
    @PostMapping("/list/page/vo")
    @Operation(summary = "分页获取商品列表")
    public BaseResponse<Page<CommodityVO>> listCommodityVOByPage(@RequestBody Commodity commodityQuery,
                                                                 @RequestParam(defaultValue = "1") long current,
                                                                 @RequestParam(defaultValue = "10") long size) {
        long size1 = Math.min(size, 20);
        Page<Commodity> commodityPage = commodityService.page(new Page<>(current, size1),
                commodityService.getQueryWrapper(commodityQuery));
        return BaseResponse.success(commodityService.getCommodityVOPage(commodityPage));
    }

    /**
     * 分页获取当前用户创建的资源列表
     */
    @PostMapping("/my/list/page/vo")
    @Operation(summary = "分页获取上架商品列表")
    public BaseResponse<Page<CommodityVO>> listMyCommodityVOByPage(@RequestBody Commodity commodityQuery,
                                                                   @RequestParam(defaultValue = "1") long current,
                                                                   @RequestParam(defaultValue = "10") long size) {
        if (commodityQuery == null) {
            commodityQuery = new Commodity();
        }
        // 只查询上架的商品
        commodityQuery.setStatus(1);
        long size1 = Math.min(size, 20);
        Page<Commodity> commodityPage = commodityService.page(new Page<>(current, size1),
                commodityService.getQueryWrapper(commodityQuery));
        return BaseResponse.success(commodityService.getCommodityVOPage(commodityPage));
    }
} 